package top.wshape1.shiziapi.uaa.controller;

import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import top.wshape1.shiziapi.common.constant.BizCodeEnum;
import top.wshape1.shiziapi.common.exception.CustomException;
import top.wshape1.shiziapi.common.exception.StatusCodeException;
import top.wshape1.shiziapi.common.utils.R;

import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author Wshape1
 * @version 1.0
 * @description
 * @since 2023-08-14
 */

/**
 * 只能捕获Controller层
 */

@Slf4j
@RestControllerAdvice
class MyGlobalExceptionController {


    @ExceptionHandler(StatusCodeException.class)
    public String handleStatusCode(StatusCodeException e, HttpServletResponse response) {
        response.setStatus(e.getStatus());
        return e.getMessage();
    }

    /**
     * 捕获 数据验证失败异常
     *
     * @param e
     * @return
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public R<Object> handlerMethodArgumentNotValidException(MethodArgumentNotValidException e) {
        BindingResult bindingResult = e.getBindingResult();

        Map<String, String> map = bindingResult.getFieldErrors().stream().collect(Collectors.toMap(
                FieldError::getField,
                fieldError -> fieldError.getDefaultMessage() != null ? fieldError.getDefaultMessage() : "格式错误"
        ));

        R<Object> r = R.instance(BizCodeEnum.INVALID_DATA_ERROR.code(), BizCodeEnum.INVALID_DATA_ERROR.msg());
        r.setData(map);
        return r;
    }

    /**
     * 全局异常捕获CustomException
     *
     * @param e
     * @return
     */
    @ExceptionHandler(CustomException.class)
    public R<?> customExceptionHandler(CustomException e) {
        log.error("CustomException异常捕获>>> {}", e.getR());
        return e.getR();
    }

    /**
     * 全局异常捕获
     *
     * @param e
     * @return
     */
    @ExceptionHandler(Exception.class)
    public R<Void> exceptionHandler(Exception e) {
        log.error("全局异常捕获>>> {}", e.getMessage());
        return R.error(e.getMessage());
    }
}
